//
//  WBStatusListViewModel.swift
//  weibo
//
//  Created by wenquan wang on 12/7/16.
//  Copyright © 2016 wenquan wang. All rights reserved.
//
private let maxPullupTryTimes = 3

import SDWebImage

class WBStatusListViewModel {
    
    lazy var statusList = [WBStatusViewModel]()
    
    private var pullupErrorTimes = 0
    
    func loadStatus(pullup: Bool = false, completion: @escaping ((isSuccess: Bool, shouldRefresh:Bool))->()){
        
        if pullup && pullupErrorTimes > maxPullupTryTimes{
            
            completion((isSuccess:false, shouldRefresh:false))
            
            return
            
        }
        
        let since_id = pullup ? 0 : statusList.first?.status.id ?? 0
        
        let max_id = !pullup ? 0 : (statusList.last?.status.id ?? 0)

        WBNetworkManager.shared.statusList(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            
            if !isSuccess{
                completion((isSuccess: false, shouldRefresh: false))
            }
            
            var array = [WBStatusViewModel]()
            
            
            for dict in list ?? [] {
                print("==================================")
                print(dict)
                guard let model = WBStatus.yy_model(with: dict) else
                { 
                    continue
                }
                array.append(WBStatusViewModel(model: model))
            }
            
            //dict to model
            /**
            guard let array = NSArray.yy_modelArray(with: WBStatus.self, json: list ?? []) as? [WBStatus] else{
                completion((isSuccess:false, shouldRefresh:false))
                return
            }
             */
            print("refresh to \(array.count)########\(array)")
            //append data
            //down refresh
            if pullup{
                self.statusList += array
            } else{
                self.statusList = (array + self.statusList)
            }
            if pullup && array.count == 0{
                self.pullupErrorTimes += 1
                completion((isSuccess:false, shouldRefresh:false))
            }
            else{
                self.cacheSingleImage(list: array, finished: completion)
                //completion((isSuccess:false, shouldRefresh:true))
            }
        }
    }
    private func cacheSingleImage(list: [WBStatusViewModel], finished: @escaping ((isSuccess: Bool, shouldRefresh:Bool))->()) {
        
        let group = DispatchGroup()
        
        var length = 0
        
        for vm in list {
            if vm.picURLs?.count != 1 {
                continue
            }
            guard let pic = vm.picURLs![0].thumbnail_pic,
                let url = URL(string: pic) else{
                    continue
            }
            //print("prepare cache image url \(pic)")
            group.enter()
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil,
                completed: { (image, _, _, _, _) in
                    
                    if let image = image, let data = UIImagePNGRepresentation(image){
                        length += data.count
                        vm.updateSingleImageSize(image: image)
                    }
                    print("cached image is \(image) length \(length)")
                    group.leave()
            })
        }
        
        group.notify(queue: DispatchQueue.main) { 
            print("image cached finished length \(length*1024)")
            finished((isSuccess:true, shouldRefresh:true))
        }
    }
}
